package com.pai4j.ugc.service.ai;

import com.pai4j.common.enums.MessageQueueTaskStatusEnum;
import com.pai4j.common.util.JsonUtil;
import com.pai4j.ugc.repository.dao.IMessageQueueTaskDAO;
import com.pai4j.ugc.repository.entity.MessageQueueTask;
import jakarta.annotation.Resource;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

/**
 * 简单的失败重试记录服务：
 *  - 保存失败时记录任务到 pai4j_mq_task，方便后续定时任务或人工处理
 */
@Slf4j
@Service
public class AiContentRetryService {

    @Resource
    private IMessageQueueTaskDAO messageQueueTaskDAO;

    public void recordPersistFail(Long momentId, Object aiContent, String errMsg) { recordPersistFail(momentId, aiContent, errMsg, null); }

    public void recordPersistFail(Long momentId, Object aiContent, String errMsg, Integer errorType) {
        try {
            MessageQueueTask task = new MessageQueueTask();
            task.setTaskId(UUID.randomUUID().toString());
            RetryPayload payload = new RetryPayload(momentId, aiContent, errMsg);
            payload.setErrorType(errorType);
            payload.setRetryCount(0);
            payload.setNextRetryTsMs(System.currentTimeMillis());
            task.setTaskJson(JsonUtil.toJsonString(payload));
            task.setTopicName("ai_content_persist_retry");
            task.setStatus(MessageQueueTaskStatusEnum.ERROR.getStatus());
            task.setCreateDate(new Date());
            task.setUpdateDate(new Date());
            messageQueueTaskDAO.save(task);
        } catch (Exception e) {
            log.error("[AI内容持久化失败重试记录也失败] momentId={}, errMsg={}", momentId, errMsg, e);
        }
    }

    @Data
    public static class RetryPayload {
        private Long momentId;
        private Object aiContent;
        private String errMsg;
        private Integer retryCount;
        private Long nextRetryTsMs;
        private Boolean exhausted;
        private Integer errorType;
        public RetryPayload(Long momentId, Object aiContent, String errMsg) {
            this.momentId = momentId;
            this.aiContent = aiContent;
            this.errMsg = errMsg;
        }
    }
}

